<template>
  <div class="pet-management-container">
    <div class="header">
      <h1>我的宠物</h1>
      <button class="add-pet-btn" @click="showAddModal">添加宠物</button>
    </div>

    <!-- 宠物列表 -->
    <div class="pet-list">
      <!-- 添加调试信息 -->
      <div v-if="pets.length === 0" class="empty-message">
        <p>暂无宠物信息，点击"添加宠物"按钮开始添加</p>
      </div>

      <div class="pet-card" v-for="pet in pets" :key="pet.id">
        <div class="pet-image">
          <img :src="getPetImage(pet.image)" alt="宠物图片" />
        </div>
        <div class="pet-info">
          <h3 class="pet-name">{{ pet.name }}</h3>
          <div class="pet-details">
            <p><span class="label">年龄：</span>{{ pet.age }}岁</p>
            <p><span class="label">性别：</span>{{ getSexText(pet.sex) }}</p>
            <p v-if="pet.birth_date">
              <span class="label">出生日期：</span
              >{{ formatDate(pet.birth_date) }}
            </p>
            <p v-if="pet.breed">
              <span class="label">品种：</span>{{ pet.breed }}
            </p>
            <p v-if="pet.weight">
              <span class="label">体重：</span>{{ pet.weight }}kg
            </p>
            <p v-if="pet.height">
              <span class="label">身高：</span>{{ pet.height }}cm
            </p>
          </div>
          <div class="pet-actions">
            <button class="edit-btn" @click="editPet(pet)">编辑</button>
            <button class="delete-btn" @click="deletePet(pet.id)">删除</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑宠物模态框 -->
    <div v-if="showModal" class="modal-overlay" @click.self="closeModal">
      <div class="modal">
        <h2>{{ editingPet ? "编辑宠物" : "添加宠物" }}</h2>
        <form @submit.prevent="submitForm">
          <div class="form-group">
            <label for="name">宠物名称 *</label>
            <input
              type="text"
              id="name"
              v-model="formData.name"
              required
              placeholder="请输入宠物名称"
            />
          </div>

          <div class="form-group">
            <label for="age">年龄 *</label>
            <input
              type="number"
              id="age"
              v-model.number="formData.age"
              required
              min="0"
              placeholder="请输入宠物年龄"
            />
          </div>

          <div class="form-group">
            <label for="sex">性别 *</label>
            <select id="sex" v-model="formData.sex" required>
              <option value="">请选择性别</option>
              <option value="male">公</option>
              <option value="female">母</option>
            </select>
          </div>

          <div class="form-group">
            <label for="image">宠物图片</label>
            <input type="file" id="image" @change="handleImageUpload" />
          </div>

          <div class="form-group">
            <label for="birth_date">出生日期</label>
            <input type="date" id="birth_date" v-model="formData.birth_date" />
          </div>

          <div class="form-group">
            <label for="breed">品种</label>
            <input
              type="text"
              id="breed"
              v-model="formData.breed"
              placeholder="请输入宠物品种"
            />
          </div>

          <div class="form-group">
            <label for="weight">重量 (kg)</label>
            <input
              type="number"
              id="weight"
              v-model.number="formData.weight"
              min="0"
              step="0.1"
              placeholder="请输入宠物重量"
            />
          </div>

          <div class="form-group">
            <label for="height">高度 (cm)</label>
            <input
              type="number"
              id="height"
              v-model.number="formData.height"
              min="0"
              step="0.1"
              placeholder="请输入宠物高度"
            />
          </div>

          <div class="form-actions">
            <button type="button" class="cancel-btn" @click="closeModal">
              取消
            </button>
            <button type="submit" class="submit-btn">提交</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axiosInstance from "../../utils/requests.js";

// 状态管理
const pets = ref([]);
const showModal = ref(false);
const editingPet = ref(null);
const selectedImage = ref(null);
const errorMessage = ref("");

// 表单数据
const formData = ref({
  name: "",
  age: 0,
  sex: "",
  image: null,
  birth_date: "",
  breed: "",
  weight: null,
  height: null,
});

// 加载宠物列表
const loadPets = async () => {
  try {
    // 清空之前的错误信息
    errorMessage.value = "";
    console.log("正在请求宠物列表，URL:", "/api/pets/pets/");
    const response = await axiosInstance.get("/api/pets/pets/");
    console.log("获取宠物列表成功，数据:", response.data);
    pets.value = response.data;
  } catch (error) {
    console.error("获取宠物列表失败:", error);
    errorMessage.value = "获取宠物列表失败，请稍后再试";
    // 清空宠物列表，防止显示缓存数据
    pets.value = [];
  }
};

// 显示添加宠物模态框
const showAddModal = () => {
  editingPet.value = null;
  resetForm();
  showModal.value = true;
};

// 编辑宠物
const editPet = (pet) => {
  console.log("编辑宠物:", pet);
  editingPet.value = pet;
  // 填充表单数据
  formData.value = {
    name: pet.name,
    age: pet.age,
    sex: pet.sex,
    image: null, // 不预填充图片，需要重新上传
    birth_date: pet.birth_date ? pet.birth_date.split("T")[0] : "", // 处理日期格式
    breed: pet.breed || "",
    weight: pet.weight || null,
    height: pet.height || null,
  };
  selectedImage.value = null;
  showModal.value = true;
};

// 处理图片上传
const handleImageUpload = (event) => {
  selectedImage.value = event.target.files[0];
};

// 提交表单
const submitForm = async () => {
  try {
    errorMessage.value = "";
    const formDataToSend = new FormData();
    // 添加表单字段
    formDataToSend.append("name", formData.value.name);
    formDataToSend.append("age", formData.value.age);
    formDataToSend.append("sex", formData.value.sex);
    // 添加可选字段
    if (selectedImage.value) {
      formDataToSend.append("image", selectedImage.value);
    }
    if (formData.value.birth_date) {
      formDataToSend.append("birth_date", formData.value.birth_date);
    }
    if (formData.value.breed) {
      formDataToSend.append("breed", formData.value.breed);
    }
    if (formData.value.weight !== null) {
      formDataToSend.append("weight", formData.value.weight);
    }
    if (formData.value.height !== null) {
      formDataToSend.append("height", formData.value.height);
    }
    let url = "/api/pets/pets/";
    if (editingPet.value) {
      url += `${editingPet.value.id}/`;
      console.log("更新宠物，URL:", url);
      await axiosInstance.put(url, formDataToSend, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
    } else {
      console.log("添加宠物，URL:", url);
      await axiosInstance.post(url, formDataToSend, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
    }

    // 刷新列表并关闭模态框
    await loadPets();
    closeModal();
  } catch (error) {
    console.error("保存宠物信息失败:", error);
    errorMessage.value = "保存宠物信息失败，请检查网络或API服务是否正常";
    // 可以添加更具体的错误提示
  }
};

// 删除宠物
const deletePet = async (id) => {
  if (confirm("确定要删除这个宠物吗？")) {
    try {
      errorMessage.value = "";
      const url = `/api/pets/pets/${id}/`;
      console.log("删除宠物，URL:", url);
      // 错误：使用了原始axios
      // await axios.delete(url);
      // 正确：使用axiosInstance
      await axiosInstance.delete(url);
      // 刷新列表
      await loadPets();
    } catch (error) {
      console.error("删除宠物失败:", error);
      errorMessage.value = "删除宠物失败，请稍后再试";
    }
  }
};

// 关闭模态框
const closeModal = () => {
  showModal.value = false;
  resetForm();
};

// 重置表单
const resetForm = () => {
  formData.value = {
    name: "",
    age: 0,
    sex: "",
    image: null,
    birth_date: "",
    breed: "",
    weight: null,
    height: null,
  };
  selectedImage.value = null;
};

// 获取宠物图片路径
const getPetImage = (imagePath) => {
  if (!imagePath) {
    // 返回默认图片，使用相对于组件的正确路径
    const defaultImageUrl = new URL(
      "../../assets/image/default-pet.jpg",
      import.meta.url
    ).href;
    return defaultImageUrl;
  }
  // 为后端返回的图片路径添加基础URL前缀
  if (typeof imagePath === "string" && !imagePath.startsWith("http")) {
    const fullImageUrl = `http://127.0.0.1:8000${imagePath}`;
    return fullImageUrl;
  }
  // 如果已经是完整URL，则直接返回
  return imagePath;
};

// 获取性别文本
const getSexText = (sex) => {
  return sex === "male" ? "公" : "母";
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleDateString("zh-CN");
};

// 初始加载宠物列表
onMounted(() => {
  console.log("组件挂载，开始加载宠物列表");
  loadPets();
});
</script>

<style lang="less" scoped>
.pet-management-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    h1 {
      color: #333;
      margin: 0;
    }

    .add-pet-btn {
      background-color: #4caf50;
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 16px;

      &:hover {
        background-color: #45a049;
      }
    }
  }

  .pet-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    .empty-message {
      grid-column: 1 / -1;
      text-align: center;
      padding: 40px 0;
      color: #666;
    }

    .pet-card {
      border: 1px solid #ddd;
      border-radius: 8px;
      padding: 16px;
      display: flex;
      flex-direction: column;
      background-color: #fff;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

      .pet-image {
        width: 100%;
        height: 200px;
        overflow: hidden;
        margin-bottom: 16px;
        border-radius: 4px;
        display: flex;
        justify-content: center;
        align-items: center;
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .pet-info {
        flex: 1;

        .pet-name {
          margin: 0 0 12px 0;
          color: #333;
          font-size: 20px;
        }

        .pet-details {
          margin-bottom: 16px;

          p {
            margin: 6px 0;
            color: #666;

            .label {
              font-weight: bold;
              color: #333;
            }
          }
        }

        .pet-actions {
          display: flex;
          gap: 10px;

          .edit-btn,
          .delete-btn {
            flex: 1;
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;

            &:hover {
              opacity: 0.9;
            }
          }

          .edit-btn {
            background-color: #2196f3;
            color: white;
          }

          .delete-btn {
            background-color: #f44336;
            color: white;
          }
        }
      }
    }
  }

  /* 模态框样式 */
  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
  }

  .modal {
    background-color: white;
    padding: 24px;
    border-radius: 8px;
    width: 90%;
    max-width: 500px;
    max-height: 90vh;
    overflow-y: auto;

    h2 {
      margin: 0 0 20px 0;
      color: #333;
    }

    .form-group {
      margin-bottom: 16px;

      label {
        display: block;
        margin-bottom: 6px;
        color: #333;
        font-weight: 500;
      }

      input,
      select {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;

        &:focus {
          outline: none;
          border-color: #2196f3;
        }
      }
    }

    .form-actions {
      display: flex;
      gap: 10px;
      justify-content: flex-end;
      margin-top: 24px;

      .cancel-btn,
      .submit-btn {
        padding: 10px 20px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;

        &:hover {
          opacity: 0.9;
        }
      }

      .cancel-btn {
        background-color: #f5f5f5;
        color: #666;
      }

      .submit-btn {
        background-color: #4caf50;
        color: white;
      }
    }
  }

  /* 错误提示样式 */
  .error-message {
    background-color: #fee;
    color: #c00;
    padding: 10px 15px;
    border-radius: 4px;
    margin-top: 15px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .pet-management-container {
    padding: 10px;

    .pet-list {
      grid-template-columns: 1fr;
    }

    .modal {
      width: 95%;
      padding: 16px;
    }
  }
}
</style>
